import { Button, Card, Form, FormProps, Input, message } from "antd";
import UploadCard from "@/pages/components/UploadCard";
import { uploadApi } from "@/api/common/index";
import { updateUserInfoApi } from "@/api/login/index";
import { API_URL } from "@/api/config";
import useStore from "@/store";
import type { FileResultType, FileType } from "@/pages/components/UploadCard/types/index.type";

const PersonalCenter = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const userInfo = useStore(state => state.userInfo);
  const setUserInfo = useStore(state => state.setUserInfo);
  const [FormRef] = Form.useForm();
  const initialValues = {
    nickname: userInfo?.nickname || userInfo?.username,
    avatar: userInfo?.avatar,
  };

  const onFinish: FormProps<{ nickname: string; avatar: string }>["onFinish"] = async values => {
    const { data } = await updateUserInfoApi({ ...values, id: userInfo?.id });
    setUserInfo(data);
    messageApi.success("提交成功");
  };
  const onSuccess = async (file: FileType) => {
    const formData = new FormData();
    formData.append("file", file as FileType);
    const { data } = await uploadApi<FormData, FileResultType>(formData);
    FormRef.setFieldsValue({ avatar: data.filePath });
  };
  return (
    <Card>
      {contextHolder}
      <Form
        name="personalCenter"
        form={FormRef}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={initialValues}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item label="用户昵称" name="nickname" rules={[{ required: true, message: "请输入用户名!" }]}>
          <Input />
        </Form.Item>

        <Form.Item label="用户头像" name="avatar" rules={[{ required: true, message: "请上传用户头像!" }]}>
          <UploadCard onSuccess={onSuccess} imgUrl={`${API_URL}/${userInfo?.avatar}`} />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            确认
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default PersonalCenter;
